/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snda.lidejia.jobflow.taskhandler.file;

import com.snda.lidejia.jobflow.exception.JobFlowException;
import com.snda.lidejia.jobflow.task.TaskData;
import com.snda.lidejia.jobflow.task.TaskHandler;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 *
 * @author lidejia
 */
public class FileReader extends TaskHandler<String, String> {

    private String getEncoding() {
        String encoding = getParam("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        return encoding;
    }

    @Override
    public TaskData<String> handler(TaskData<String> inputs) throws JobFlowException {
        try {
            TaskData<String> output = new TaskData<String>();
            for (String file : inputs) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding()));
                try {
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        output.addData(line);
                    }
                } finally {
                    reader.close();
                }
            }
            return output;
        } catch (Exception e) {
            throw new JobFlowException(e);
        }
    }
}
